package com.hd.crdao.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.adapter.BrandAdapater;
import com.hd.crdao.adapter.ConditionAdapter;
import com.hd.crdao.adapter.OldCarInfoAdapter;
import com.hd.crdao.adapter.SeriesAdapater;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.base.MyBaseAdapter;
import com.hd.crdao.bean.BrandInfoBean;
import com.hd.crdao.bean.CarInfoListBean;
import com.hd.crdao.bean.OldCarInfoBean;
import com.hd.crdao.bean.SearchBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.MultiLineRadioGroup;
import com.hd.crdao.view.MyListView;
import com.hd.crdao.view.SideBar;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/8/3 0003
 */

public class AllCarSourActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {


    public MyListView mMyListView;
    public CheckBox mCbSort, mCbBrank, mCbPrice, mCbFilter; // 功能条控件
    public LinearLayout mLayout;
    private BrandInfoBean mBrandInfoBean;
    private Handler mHandler = new Handler();
    public OnRefreshListener mOnRefreshListener;
    public MyBaseAdapter<String> mFilterAdapter;
    public EditText mMinPrice;
    public EditText mMaxPrice;
    public String[] mPriceArray = new String[]{"", ""};
    RelativeLayout mProgreassbarLayout;
    ProgressBar mProgreassbar;
    TextView mLoadState;
    public List<CarInfoListBean> mOldCarInfoList;
    public OldCarInfoAdapter mOldCarInfoAdapter;
    /**
     * 储存条件的集合
     */
    public HashMap<String, String> mFilters = new HashMap<>();
    public ConditionAdapter mConditionAdapter;
    /**
     * 给GV显示筛选条件的集合
     */
    private ArrayList<String> conditions = new ArrayList<>();
    public LinearLayout mConditions_layout;
    public GridView conditionGV;
    public Button mResetCondition;
    public ListView listBrand;
    public TextView mTakeSearch;
    public String storeId;
    public ImageView mGoback;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_allcarsource;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);  //注册
        storeId = getIntent().getStringExtra("storeId");
        mOnRefreshListener = new OnRefreshListener();
        mLayout = (LinearLayout) findViewById(R.id.ll_submenu);
        mTakeSearch = (TextView) findViewById(R.id.takeSearch);
        mGoback = (ImageView) findViewById(R.id.goback);
        //进度条显示
        mProgreassbarLayout = (RelativeLayout) findViewById(R.id.progreassbar_layout);
        mProgreassbar = (ProgressBar) findViewById(R.id.progreassbar);
        mLoadState = (TextView) findViewById(R.id.load_state);
       /* 功能条控件 */
        mCbSort = (CheckBox) findViewById(R.id.cb_sort);
        mCbBrank = (CheckBox) findViewById(R.id.cb_brand);
        mCbPrice = (CheckBox) findViewById(R.id.cb_price);
        mCbFilter = (CheckBox) findViewById(R.id.cb_filter);
        /* 内容 */
        mMyListView = (MyListView) findViewById(R.id.carList);
        mMyListView.setonRefreshListener(mOnRefreshListener);
        //加入条件的控件
        mConditions_layout = (LinearLayout) findViewById(R.id.conditioons);
        conditionGV = (GridView) findViewById(R.id.conditioonGV);
        mResetCondition = (Button) findViewById(R.id.resetcondition);
        mConditionAdapter = new ConditionAdapter(conditions);
        // solveParamsFromMain();
    }

    /**
     * 处理从首页跳转过来的条件
     */
    private void solveParamsFromMain(String passMsg) {
        if (!TextUtils.isEmpty(passMsg)) {
            if (passMsg.contains("万")) {
                String[] price = parsePrice(passMsg);
                deleteCommonCondition("minPrice");
                deleteCommonCondition("maxPrice");
                mFilters.put("minPrice", price[0]);
                mFilters.put("maxPrice", price[1]);
            } else {
                deleteCommonCondition("brand");
                if (TextUtils.equals("全部", passMsg)) {
                    mFilters.put("brand", "不限");
                } else {
                    mFilters.put("brand", passMsg);
                }

            }
        }
        UpdateCondition(passMsg);
        chooseConditionLoadData();

    }

    /**
     * 加载数据
     */
    private void loadData() {
        mProgreassbarLayout.setVisibility(View.VISIBLE);
        HashMap<String, String> map = new HashMap<>();
        map.put("appFlag", "true");
        map.put("sign", Constants.SIGN);
        map.put("carBusinessId", Config.businessId);
        map.put("storeId", storeId);
        changeConditionLoadData(map);
        OkHttpUtils.post().url(Constants.OLDERCAR_URL).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mProgreassbarLayout.setVisibility(View.GONE);
                mLoadState.setText("网络开了个小差");
                ALog.d("网络开了个小差");
            }

            @Override
            public void onResponse(String response, int id) {
                //   ALog.d(response);
                Gson gson = new Gson();
                OldCarInfoBean oldCarInfoBean = gson.fromJson(response, OldCarInfoBean.class);
                mOldCarInfoList = oldCarInfoBean.getCarInfoList();
                mOldCarInfoAdapter = new OldCarInfoAdapter(mOldCarInfoList);
                mMyListView.setAdapter(mOldCarInfoAdapter);
                if (oldCarInfoBean.getSuccess() == 0) {
                    mProgreassbarLayout.setVisibility(View.GONE);
                    mLoadState.setText(oldCarInfoBean.getMessage());
                }
            }


        });
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initListener() {
        mCbSort.setOnCheckedChangeListener(this);
        mCbBrank.setOnCheckedChangeListener(this);
        mCbPrice.setOnCheckedChangeListener(this);
        mCbFilter.setOnCheckedChangeListener(this);

        mMyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String carInfoId = mOldCarInfoList.get(position - 1).getId();
                Intent intent = new Intent(UIUtils.getContext(), CarDetailsActivity.class);
                intent.putExtra("carid", carInfoId);
                ALog.d(carInfoId);
                startActivity(intent);

            }
        });
        mResetCondition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {       //重置条件
                conditions.clear();
                mFilters.clear();
                mConditionAdapter.notifyDataSetChanged();
                mConditions_layout.setVisibility(View.GONE);
                chooseConditionLoadData();
            }
        });

        conditionGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {      //移除当前点击条目这个条件
                String singleCondition = conditions.get(position);
                conditions.remove(position);
                mConditionAdapter.notifyDataSetChanged();
                if (conditions.size() == 0) {
                    mConditions_layout.setVisibility(View.GONE);
                }

                //清除了条件 需要清空条件并重新加载数据
                // mFilters.remove()
                ALog.d(singleCondition);
                for (Map.Entry<String, String> entry : mFilters.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    if (mBrandInfoBean != null) {
                        for (int i = 0; i < mBrandInfoBean.getRows().size(); i++) {
                            BrandInfoBean.RowsBean rowsBean = mBrandInfoBean.getRows().get(i);
                            if (TextUtils.equals(singleCondition, rowsBean.getVcBrand())) {
                                mFilters.put("brand", "");
                            } else if (singleCondition.equals(rowsBean.getVcSeries())) {
                                mFilters.put("series", "");
                            }
                        }
                    }
                    if (singleCondition.contains("万")) {
                        if (singleCondition.contains("公里")) {
                            mFilters.put("minMileage", "");
                            mFilters.put("maxMileage", "");
                        } else {
                            mFilters.put("minPrice", "");
                            mFilters.put("maxPrice", "");
                        }

                    } else if (singleCondition.contains(value)) {
                        if (TextUtils.equals(key, "series") | TextUtils.equals(key, "brand")) {
                            continue;
                        }
                        mFilters.put(key, "");
                    }
                }
                chooseConditionLoadData();

            }
        });

        mTakeSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UIUtils.getContext(), SearchActivity.class));
            }
        });
        mGoback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


    }


    @Override
    protected void initData() {
        mOnRefreshListener.onRefresh();
        OkHttpUtils.post().url(Constants.BRANTYPEURL)
                .addParams("data", "1")
                .addParams("sign", Constants.SIGN)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("数据加载失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                Gson gson = new Gson();
                mBrandInfoBean = gson.fromJson(response, BrandInfoBean.class);
            }
        });
    }

    /**
     * 更新筛选条件
     *
     * @param condition 选择条件显示在布局上
     */
    private void UpdateCondition(String... condition) {
        mConditions_layout.setVisibility(View.VISIBLE);
      /*  for (int i = 0; i < 10; i++) {
            conditions.add(i,"测试"+i);
        }*/
        for (String aCondition : condition) {
            if (!TextUtils.equals(aCondition, "不限")) {
                conditions.add(aCondition);
            }
        }
        if (conditions.size() == 0) {
            mConditions_layout.setVisibility(View.GONE);
        }
        conditionGV.setAdapter(mConditionAdapter);
        mConditionAdapter.notifyDataSetChanged();
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_sort:
                showSortPop(R.array.sort);

                break;
            case R.id.cb_brand:
                showBrandPop();
                break;
            case R.id.cb_price:
                showPricePop();
                break;
            case R.id.cb_filter:
                showFilterPop();
                break;
            default:
                break;
        }
    }


    /**
     * 进行排序操作  存值完成
     *
     * @param ArrayRes 字符数组
     */
    private void showSortPop(int ArrayRes) {
        final List<String> list = new ArrayList<>();
        String[] sort = UIUtils.getStrings(ArrayRes);
        Collections.addAll(list, sort);
        View popView = View.inflate(UIUtils.getContext(), R.layout.sort_item, null);
        ListView listView = (ListView) popView.findViewById(R.id.listview);
        listView.setVerticalScrollBarEnabled(true);  //不活动的时候隐藏滚动条，活动的时候也隐藏滚动条
        mFilterAdapter = new FilterAdapter(list, true);
        listView.setAdapter(mFilterAdapter);
        final PopupWindow popupWindow = getPopupWindow(popView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String condition = list.get(position);
                mCbSort.setText(condition);
                if (position == 0) {
                    mFilters.put("orderBy", "");
                } else if (position == 1) {
                    mFilters.put("orderBy", "a.create_date ASC");
                } else if (position == 2) {
                    mFilters.put("orderBy", "a.ci_expectprice DESC");
                } else if (position == 3) {
                    mFilters.put("orderBy", "a.ci_expectprice ASC");
                } else if (position == 4) {
                    mFilters.put("orderBy", "a.ci_mileage ASC");
                } else if (position == 5) {
                    mFilters.put("orderBy", "a.ci_mileage DESC");
                }
                popupWindow.dismiss();
                ALog.d("选择的条件是" + mFilters.get("orderBy"));
                //loadData(null, null, null, null, null, null, null, null, null, null, null, null, null, mFilters.get("orderBy"));
                chooseConditionLoadData();
            }
        });


    }


    /**
     * 进行筛选按钮操作 存值完成
     */
    private void showFilterPop() {
        final View popView = View.inflate(UIUtils.getContext(), R.layout.filter_item, null);
        final PopupWindow popupWindow = getPopupWindow(popView);
        final MultiLineRadioGroup brand = (MultiLineRadioGroup) popView.findViewById(R.id.mrg_brand);
        final MultiLineRadioGroup box = (MultiLineRadioGroup) popView.findViewById(R.id.mrg_box);
        final MultiLineRadioGroup mileage = (MultiLineRadioGroup) popView.findViewById(R.id.mrg_mileage);
        final MultiLineRadioGroup paiLiang = (MultiLineRadioGroup) popView.findViewById(R.id.mrg_pailiang);
        final MultiLineRadioGroup paiFang = (MultiLineRadioGroup) popView.findViewById(R.id.mrg_paifang);
        TextView tvClear = (TextView) popView.findViewById(R.id.tv_clear);
        TextView tvSure = (TextView) popView.findViewById(R.id.tv_sure);
        tvClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                brand.clearChecked();
                box.clearChecked();
                mileage.clearChecked();
                paiLiang.clearChecked();
                paiFang.clearChecked();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                List<String> levels = brand.getCheckedValues();  //车型
                List<String> greBoxs = box.getCheckedValues();  //变速箱
                List<String> mileages = mileage.getCheckedValues();//公里数
                List<String> outputVolume = paiLiang.getCheckedValues();    //排量
                List<String> enviStandards = paiFang.getCheckedValues();       //排放
               /* String gearBox, String minOutputl, String maxOutputl,
                        String enviStandard, String level*/
                popupWindow.dismiss();
                deleteCommonCondition("level");
                deleteCommonCondition("gearBox");
                deleteCommonCondition("enviStandard");
                //给公里数去重
                String oldMinMileage = mFilters.get("minMileage");
                String oldMaxMileage = mFilters.get("maxMileage");
                if (!TextUtils.isEmpty(oldMinMileage) && !TextUtils.isEmpty(oldMaxMileage)) {
                    String mileage = oldMinMileage + "-" + oldMaxMileage + "万公里";
                    int indexOf = conditions.indexOf(mileage);
                    if (indexOf != -1) {
                        conditions.remove(indexOf);
                    }
                }
                //给排量参数去重
                for (int i = 0; i < conditions.size(); i++) {
                    String condition = conditions.get(i);
                    if (condition.contains("L")) {
                        conditions.remove(i);
                    }
                }

                //筛选条件重新赋值
                SaveParams("level", levels);    //车型
                SaveParams("gearBox", greBoxs);
                SaveParams("enviStandard", enviStandards);
                if (mileages.size() != 0) {
                    String mileage = mileages.get(0);
                    if (mileage.length() > 2) {
                        // mileage = mileage.replace("万公里", "");//由于没有万公里
                        String[] split = mileage.split("-");
                        String minMileage = split[0];
                        String maxMileage = split[1];
                        mFilters.put("minMileage", minMileage);
                        mFilters.put("maxMileage", maxMileage);
                    }
                }
                if (outputVolume.size() != 0) {
                    String output = outputVolume.get(0);
                    if (output.length() > 6) {
                        ALog.d(output);
                        output = output.replace("L", "");
                        String[] split = output.split("-");
                        String minOutputl = split[0];
                        String maxOutputl = split[1];
                        mFilters.put("minOutputl", minOutputl);
                        mFilters.put("maxOutputl", maxOutputl);
                    } else {
                        if (TextUtils.equals(output, "1.0L以下")) {
                            mFilters.put("minOutputl", "0.0");
                            mFilters.put("maxOutputl", "1.0");
                        } else {
                            mFilters.put("minOutputl", "4.0");
                            mFilters.put("maxOutputl", "10.0");
                        }
                    }
                }


                UpdateCondition(
                        levels.size() == 0 ? "不限" : levels.get(0),
                        greBoxs.size() == 0 ? "不限" : greBoxs.get(0),
                        mileages.size() == 0 ? "不限" : mileages.get(0),
                        outputVolume.size() == 0 ? "不限" : outputVolume.get(0),
                        enviStandards.size() == 0 ? "不限" : enviStandards.get(0));

              /*  ALog.d(mFilters.get("level"));
                ALog.d(mFilters.get("gearBox"));
                ALog.d(mFilters.get("mileage"));
                ALog.d(mFilters.get("output"));
                ALog.d(mFilters.get("enviStandard"));*/
                //筛选之后数据展示
                chooseConditionLoadData();


            }
        });


    }

    /**
     * 删除相同的条件 保留一个条件
     * 从布局里面删除
     *
     * @param condition
     */
    private void deleteCommonCondition(String condition) {
        int indexOf = conditions.indexOf(mFilters.get(condition));
        if (indexOf != -1) {
            conditions.remove(indexOf);
        }
    }

    /**
     * 选择条件以加载数据的方法
     */
    private void chooseConditionLoadData() {
        loadData();
    }

    /**
     * 保存一些参数,抽取的方法
     *
     * @param key
     * @param params
     */
    private void SaveParams(String key, List<String> params) {
        if (params.size() != 0) {
            mFilters.put(key, params.get(0));
        } else {
            mFilters.put(key, "");
        }
    }


    /**
     * 进行品牌选择  存值完成
     */
    private void showBrandPop() {
        View popView = View.inflate(UIUtils.getContext(), R.layout.brand_item, null);
        listBrand = (ListView) popView.findViewById(R.id.list_brand);
        final ListView listSeries = (ListView) popView.findViewById(R.id.list_series);

        SideBar sideBar = (SideBar) popView.findViewById(R.id.side_bar);
        sideBar.setOnStrSelectCallBack(new SideBar.ISideBarSelectCallBack() {
            @Override
            public void onSelectStr(int index, String selectStr) {
                for (int i = 0; i < mBrandInfoBean.getRows().size(); i++) {
                    if (selectStr.equalsIgnoreCase(mBrandInfoBean.getRows().get(i).getVcFirst())) {
                        listBrand.setSelection(i); // 选择到首字母出现的位置
                        return;
                    }
                }
            }
        });
        listBrand.setVerticalScrollBarEnabled(true);  //不活动的时候隐藏滚动条，活动的时候也隐藏滚动条
        listSeries.setVerticalScrollBarEnabled(true);  //不活动的时候隐藏滚动条，活动的时候也隐藏滚动条
        listBrand.setAdapter(new BrandAdapater(mBrandInfoBean.getRows()));

        final PopupWindow popupWindow = getPopupWindow(popView);
        listBrand.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final BrandInfoBean.RowsBean rowsBean = mBrandInfoBean.getRows().get(position);
                //点击条目之后根据参数请求接口  刷新适配器显示数据
                String vcBrand = rowsBean.getVcBrand();
                deleteCommonCondition("brand");
                mFilters.put("brand", vcBrand);
                UpdateCondition(vcBrand);
                OkHttpUtils.post().url(Constants.BRANTYPEURL)
                        .addParams("data", "2~" + vcBrand)
                        .addParams("sign", Constants.SIGN)
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show("数据加载失败,请检查网络...");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        final BrandInfoBean seriesInfoBean = gson.fromJson(response, BrandInfoBean.class);
                        List<BrandInfoBean.RowsBean> rows = seriesInfoBean.getRows();
                        BrandInfoBean.RowsBean bean = new BrandInfoBean.RowsBean();
                        bean.setVcSeries("不限");
                        rows.add(0, bean);
                        listSeries.setAdapter(new SeriesAdapater(rows));

                        listSeries.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                String vcSeries = seriesInfoBean.getRows().get(position).getVcSeries();
                                deleteCommonCondition("series");    //删除相同条件
                                mFilters.put("series", vcSeries); //放值
                                UpdateCondition(vcSeries);  //更新条件
                                popupWindow.dismiss();
                                chooseConditionLoadData();  //重新请求加载数据

                            }
                        });
                    }
                });
            }


        });
    }


    /**
     * 价格筛选  已加入布局
     */
    private void showPricePop() {
        final List<String> list = new ArrayList<>();
        String[] price = UIUtils.getStrings(R.array.price);
        Collections.addAll(list, price);

        View popView = View.inflate(UIUtils.getContext(), R.layout.price_item, null);
        mMinPrice = (EditText) popView.findViewById(R.id.min_price);
        mMaxPrice = (EditText) popView.findViewById(R.id.max_price);
        TextView tvSure = (TextView) popView.findViewById(R.id.sure);
        GridView gridView = (GridView) popView.findViewById(R.id.gridview_pic);

        gridView.setAdapter(new FilterAdapter(list, false));
        final PopupWindow popupWindow = getPopupWindow(popView);

        //点击确定的时候获取输入框的价格信息  KO
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String minPrice = mMinPrice.getText().toString().trim();
                String maxPrice = mMaxPrice.getText().toString().trim();
                mPriceArray[0] = minPrice;
                mPriceArray[1] = maxPrice;
                popupWindow.dismiss();
                String oldMinPrice = mFilters.get("minPrice");
                String oldMaxPrice = mFilters.get("maxPrice");
                if (!TextUtils.isEmpty(oldMinPrice) && !TextUtils.isEmpty(oldMaxPrice)) {
                    String temp = oldMinPrice + "-" + oldMaxPrice + "万";
                    int indexOf = conditions.indexOf(temp);
                    if (indexOf != -1) {
                        conditions.remove(indexOf);
                    }
                }
                mFilters.put("minPrice", minPrice);
                mFilters.put("maxPrice", maxPrice);
                UpdateCondition(minPrice + "-" + maxPrice + "万");
                chooseConditionLoadData();
            }
        });
        /*筛选条件已经搞定*/
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String price = list.get(position);
                mPriceArray = parsePrice(price);
                popupWindow.dismiss();
                for (String priceDesc : list) {
                    int indexOf = conditions.indexOf(priceDesc);
                    if (indexOf != -1) {
                        conditions.remove(indexOf);
                    }
                }
                mFilters.put("minPrice", mPriceArray[0]);
                mFilters.put("maxPrice", mPriceArray[1]);
                UpdateCondition(price);
                chooseConditionLoadData();
            }
        });

    }

    /**
     * 判断传入的参数是否为空 ,貌似暂时用不上
     *
     * @param map
     * @param key
     */
    public void judgeEmpty(HashMap<String, String> map, String key) {
        if (!TextUtils.isEmpty(key)) {
            map.put(key + "", key);
        }
    }

    /**
     * 创建一个popupwindow
     *
     * @param popView pop视图
     * @return
     */
    @NonNull
    private PopupWindow getPopupWindow(View popView) {
        PopupWindow popupWindow = new PopupWindow(popView, getResources().getDisplayMetrics().widthPixels, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(Color.parseColor("#ffffff"));
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.showAsDropDown(mLayout);
        return popupWindow;
    }


    /**
     * 销毁eventbus对象
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);  //反注册
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void ReciveMessage(SearchBean searchBean) {
        ALog.d(searchBean.getValue() + "!!!!!!!!!!!!!!!!!");
        // mTvProvince.setText(eventBean.getCityName());
        //   UpdateCondition(eventBean.getCityName());
        solveParamsFromMain(searchBean.getValue());

    }


    private class RefreshRunnable implements Runnable {
        @Override
        public void run() {
            //重新加载数据,然后刷新适配器 然后更新完成
            // mFilters.clear();
            chooseConditionLoadData();
            mProgreassbarLayout.setVisibility(View.GONE);
            mMyListView.onRefreshComplete();
        }
    }

    /**
     * 下拉刷新的监听
     */
    private class OnRefreshListener implements MyListView.OnRefreshListener {

        @Override
        public void onRefresh() {
            //  mProgreassbarLayout.setVisibility(View.VISIBLE);
            mHandler.postDelayed(new RefreshRunnable(), 1000);
        }
    }

    /**
     * 筛选的适配器
     */
    private class FilterAdapter extends MyBaseAdapter<String> {
        private boolean isSingle;

        FilterAdapter(List<String> dataSets, boolean isSingle) {
            super(dataSets);
            this.isSingle = isSingle;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                if (isSingle) {
                    convertView = View.inflate(UIUtils.getContext(), R.layout.item_sort_pop, null);
                    //找到控件
                    holder.mTextView = (TextView) convertView.findViewById(R.id.tv_sort);
                } else {
                    convertView = View.inflate(UIUtils.getContext(), R.layout.item_price_pop, null);
                    //找到控件
                    holder.mTextView = (TextView) convertView.findViewById(R.id.tv_price);
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mTextView.setText(mDataSets.get(position));
            return convertView;
        }


    }

    public class ViewHolder {
        TextView mTextView;
    }

    /**
     * 改变加载的条件
     * @param map
     */
    public void changeConditionLoadData(HashMap<String, String> map) {
        for (Map.Entry<String, String> entry : mFilters.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (TextUtils.equals("不限", value)) {
                map.put(key, "");
            } else {
                map.put(key, value);
            }
            ALog.d("key= " + key + ",value= " + value);
        }

    }

    /**
     * 解析价格的方法,直接返回最小价格和最大价格
     *
     * @param price
     * @return
     */
    public String[] parsePrice(String price) {
        if (TextUtils.equals(price, "不限")) {
            return new String[]{"", ""};
        } else {
            price = price.replace("万", "");
        }
        if (price.contains("以下")) {
            String num = price.replace("以下", "");
            return new String[]{"0", num};
        } else if (price.contains("以上")) {
            String num = price.replace("以上", "");
            return new String[]{num, "999"};
        } else {
            return price.split("-");
        }
    }


}
